/*
  "name": "大山后台管理系统",
  "version": "1.0",
  "description": "大山中后台管理系统",
  "author": "大山",
  "date": "2023-04-04",
  "license": "MIT",
*/

const bodyParser = require('body-parser');
const jsonParser = bodyParser.json({ limit: '1000mb' });
const resbody = require('../utils/resbody');
const utils = require('../utils/utils');
const token = require('../utils/token');
const connection = require('../utils/sql');
const mysql = require('mysql');
const escape = mysql.escape;
const jwt = require("jsonwebtoken");
const { log } = require('debug/src/node');

module.exports = (app) => {
	// 验证token
	const whiteList = ['/api/login'];
	let userTokenData;
	
	app.use((req,res,next) => {
		if(!whiteList.includes(req.url)) {
			token.verifyToken(req.headers.authorization).then(res => {
				userTokenData = res
				next()
			}).catch(e => {
				// token过期时的err值："message": "jwt expired",
				// token无效时的err值："message": "jwt malformed | invalid token | invalid signature",
				// 没有token的err值："message": "jwt must be provided"
				// console.log(token.tokenMsg(), e.message)
				let msg = token.tokenMsg().find(item => item.type === e.message)['msg'];
				// res.status(200).send(res.json(resbody.getFailResult({}, msg)))
				res.json(resbody.getFailResult({}, msg, 401))
			})
		} else {
			next()
		}
	})
	
	// 查询路由/菜单
	app.get('/api/menuList',(req,res) => {
	    const sql = `SELECT * FROM sysMenu order by order_num asc`;
	    connection(sql, (error, result, fileds) =>{
	    	console.log(error);
	        if(error) {
	            res.json(resbody.getFailResult(error))
	        }else{
	            // 返回目录和菜单，按钮权限过滤
	            res.json(resbody.getSuccessResult(result))
	        }
	    })
	})
	
	// 查询路由/菜单列表
	app.get('/api/getRouters',(req,res) => {
	    const sql = `SELECT * FROM sysMenu where menu_type = 'M' or menu_type = 'C'`;
	    connection(sql, (error, result, fileds) =>{
	    	console.log(error);
	        if(error) {
	            res.json(resbody.getFailResult(error))
	        }else{
	            // 返回目录和菜单，按钮权限过滤
	    		let data = result.filter(item => item.menu_type === 'M' || item.menu_type === 'C').map(item => ({
					alwaysShow: item.parent_id === 0 ? true : undefined,
					component: item.parent_id === 0 ? "Layout" : item.component,
					hidden: item.visible === '0' ? false : true,
					meta: {
						title: item.menu_name,
						icon: item.icon,
						link: item.is_frame === 1 ? null : item.path,
						noCache: item.is_cache === 0 ? false : true,
					},
					name: utils.titleCase(item.path),
					path: `/${item.path}`,
					redirect: item.parent_id === 0 ? 'noRedirect' : undefined,
					menu_id: item.menu_id,
					parent_id: item.parent_id,
				}))
				data = utils.handleMenuTree(data, 'menu_id', 'parent_id');
	            res.json(resbody.getSuccessResult(data))
	        }
	    })
	})
	
	// 菜单 - 获取单条数据
	app.get('/api/menu/:id', (req, res, next) => {
		const { id } = req.params
		const sql = `SELECT * FROM sysMenu WHERE menu_id = ${escape(id)}`
		connection(sql, (error, result, fileds) => {
		    if(error) {
		        console.log(error)
		        res.json(resbody.getFailResult(error))
		    }else{
				// 返回
		        res.json(resbody.getSuccessResult(result[0]))
		    }
		})
	})
	
	// 菜单 - 添加数据
	app.post('/api/menu', (req,res) => {
		// 接收参数
		const { menu_name, parent_id, order_num, path, component, query_param, is_frame, is_cache, menu_type, visible, status, perms, icon, remark } = req.body
		// const id = utils.randomNumber();
		
		// 判断验证
		if (!menu_name) {
			res.json(resbody.getFailResult({}, '请您输入菜单名称', 0))
		    return false
		}
		
		// 参数作二次处理，无则下一步
		const data = {
			menu_name,
			parent_id: parent_id === '' ? 0 : parent_id,
			order_num,
			path,
			component,
			query_param,
			is_frame,
			is_cache,
			menu_type,
			visible,
			status,
			perms,
			icon,
			remark
		}
		
		const sql = 'INSERT INTO sysMenu SET?';
		connection(sql, data, (error, result, fileds) => {
		    if(error) {
		        console.log(error)
		        res.json(resbody.getFailResult(error))
		    } else {
		        // 返回
		        res.json(resbody.getSuccessResult(result))
				utils.recordOperaLog(connection, `添加菜单`, userTokenData)
		    }
		})
	})
	
	// 菜单 - 更新数据
	app.put('/api/menu/', (req, res) => {
		let keysString = utils.updateDataSql(req.body)
		
	    const sql = `UPDATE sysMenu SET ${keysString}WHERE menu_id = '${req.body.menu_id}'`;
	    connection(sql,(error, result, fileds) => {
	        if(error) {
	            console.log(error)
	            res.json(resbody.getFailResult(error))
	        }else{
	            res.json(resbody.getSuccessResult(result))
				utils.recordOperaLog(connection, `更新菜单`, userTokenData)
	        }
	    })
	})

	// 菜单 - 删除数据
	app.delete('/api/menuDelete/:id',(req,res) => {
		const { id } = req.params;
		
		const getSql = `SELECT * FROM sysMenu`
	    const deleteSql = `DELETE FROM sysMenu WHERE menu_id = ${escape(id)}`
		
		connection(getSql, (error, result, fileds) => {
		    if(error) {
		        console.log(error)
		        res.json(resbody.getFailResult(error))
		    }else{
				// 返回
				let isChildren = result.filter(item => item.parent_id === parseFloat(id) && (item.menu_type === 'M' || item.menu_type === 'C'))
				console.log(isChildren, 11)
				// 判断它有没有子级菜单
				if (isChildren.length >= 1) {
					// isChildren = isChildren.map(item => {
					// 	return item.menu_type === 'M' || item.menu_type === 'C'
					// })
					res.json(resbody.getFailResult({}, '此菜单下还有子级菜单/按钮，不可删除', 0))
					return false
				}

				connection(deleteSql, (error, result, fileds) => {
				    if(error){
				        console.log(error)
				        res.json(resbody.getFailResult(error))
				    }else{
				        res.json(resbody.getSuccessResult({}, '删除成功'))
						utils.recordOperaLog(connection, `删除菜单`, userTokenData)
				    }
				})
		    }
		})
	    
	})
}
